// gotcpspy starts a tcp server on localhost and outputs incomming data 
// from incomming connections to stdout.
package main

import (
	"fmt"
	"log"
	"net"
	"os"
)

func doReads(conn net.Conn) {
	resp := make([]byte, 4096)
	for {
		r, err := conn.Read(resp)
		if r > 0 {
			fmt.Print(string(resp[:r]))
		}
		if err != nil {
			fmt.Println("Connection closed:", err)
			break
		}
	}
}

func doAccepts(ln net.Listener) {
	for {
		conn, err := ln.Accept()
		if err != nil {
			fmt.Println("Accept failed:", err)
			continue
		}
		fmt.Printf("New client (local: %v), (remote: %v)\n", conn.LocalAddr(), conn.RemoteAddr())
		go doReads(conn)
	}
}

func main() {
	if len(os.Args) != 2 {
		log.Fatalln("Usage:\n gotcpspy <port>")
	}
	ln, err := net.Listen("tcp", ":"+os.Args[1])
	if err != nil {
		log.Fatalln("Error listening:", err)
	}
	fmt.Printf("Listening on port %s. Hit any key to exit program.\n", os.Args[1])
	go doAccepts(ln)

	fmt.Scanln()
}
